package com.rem.rabbitmq.boot.Bconfirm;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;

/**
 * @author Rem
 * @date 2021-12-30
 */

@Slf4j
@RestController
@RequestMapping("/comfirm")
@Api(tags = "发布确认")
public class ConfirmController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @ApiOperation(value = "发送一条确认的消息")
    @GetMapping("/sendMsg/{message}")
    public void sendMsg(@PathVariable String message) {
        log.info("当前时间：{}，发送消息开始:{}", LocalDateTime.now(), message);

        CorrelationData correlationData = new CorrelationData("111");
        rabbitTemplate.convertAndSend(ConfirmConfig.CONFIRM_EXCHANGE, ConfirmConfig.CONFIRM_ROUTING_KEY, ConfirmConfig.CONFIRM_ROUTING_KEY + ":" + message, correlationData);

        /**
         * 发送到一个假的exchange上
         * 消息ack为false
         */
        CorrelationData correlationData2 = new CorrelationData("222");

        rabbitTemplate.convertAndSend("FAKE_EXCHANGE", ConfirmConfig.CONFIRM_ROUTING_KEY, ConfirmConfig.CONFIRM_ROUTING_KEY + ":" + message, correlationData2);

        /**
         * 发送到一个假的routingKey上
         * 消息会被退回
         */
        CorrelationData correlationData3 = new CorrelationData("333");
        rabbitTemplate.convertAndSend(ConfirmConfig.CONFIRM_EXCHANGE, "FAKE_ROUTING_KEY", "FAKE_ROUTING_KEY" + ":" + message, correlationData3);
        log.info("当前时间：{}，发送消息完毕:{}", LocalDateTime.now(), message);
    }


    @ApiOperation(value = "发送一条消费者确认的消息")
    @GetMapping("/sendMsg/consumer/{message}")
    public void sendMsg2(@PathVariable String message) {
        log.info("当前时间：{}，发送消息开始:{}", LocalDateTime.now(), message);
        MessagePostProcessor me = message1 -> {
            message1.getMessageProperties().setRedelivered(false);
            return message1;
        };
        rabbitTemplate.convertAndSend("amq.direct", "hello", message, me);
        log.info("当前时间：{}，发送消息完毕:{}", LocalDateTime.now(), message);
    }


}
